package com.boot.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class LoginAttemptService {

    private static final int MAX_ATTEMPTS = 5;
    private static final long LOCK_TIME_MILLIS = 15 * 60 * 1000; // 15分钟

    // IP -> 尝试次数
    private final Map<String, Integer> attempts = new ConcurrentHashMap<>();
    // IP -> 锁定开始时间（毫秒）
    private final Map<String, Long> lockTimes = new ConcurrentHashMap<>();

    /**
     * 记录一次失败尝试
     */
    public void loginFailed(String ip) {
        if (isBlocked(ip)) return; // 已被锁，不再增加

        attempts.merge(ip, 1, Integer::sum);
        if (attempts.get(ip) >= MAX_ATTEMPTS) {
            lockTimes.put(ip, System.currentTimeMillis());
            attempts.remove(ip);
            log.info("IP " + ip + " 因多次失败登录被锁定");
        }
    }

    /**
     * 登录成功时清除记录
     */
    public void loginSuccess(String ip) {
        attempts.remove(ip);
        lockTimes.remove(ip);
    }

    /**
     * 当前 IP 是否被锁定
     */
    public boolean isBlocked(String ip) {
        Long lockStart = lockTimes.get(ip);
        if (lockStart == null) return false;

        if (System.currentTimeMillis() - lockStart > LOCK_TIME_MILLIS) {
            // 超时自动解锁
            lockTimes.remove(ip);
            return false;
        }
        return true;
    }
}
